# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10001632': {  # 御投支付接的是loki，支付方式有：支付宝，快捷，qqh5.http://www.yutoutz.com/merchant/login
        'API_KEY': '8d1b7191502746a2b35614b3e2eab66c',
        'gateway': 'http://xs.szjietu.com/gateway/bankTrade/prepay',
        'query_gateway': 'http://xs.szjietu.com/gateway/mer/order/query',
    },
    '10001703': {  # 御投支付接的是loki，支付方式有：支付宝，快捷，qqh5.http://www.yutoutz.com/merchant/login
        'API_KEY': 'f1142b3af60d46368f182c9a2e4b3ba0',
        'gateway': 'http://xs.szjietu.com/gateway/bankTrade/prepay',
        'query_gateway': 'http://xs.szjietu.com/gateway/mer/order/query',
    },
    '10001704': {  # 御投支付接的是loki，支付方式有：支付宝，快捷，qqh5.http://www.yutoutz.com/merchant/login
        'API_KEY': '56b40d1bc4214a1bb14f4850f08bbffc',
        'gateway': 'http://xs.szjietu.com/gateway/bankTrade/prepay',
        'query_gateway': 'http://xs.szjietu.com/gateway/mer/order/query',
    },
    '10001705': {  # 御投支付接的是loki，支付方式有：支付宝，快捷，qqh5.http://www.yutoutz.com/merchant/login
        'API_KEY': 'b4dfe0619ce2420eb47763c15d30000f',
        'gateway': 'http://xs.szjietu.com/gateway/bankTrade/prepay',
        'query_gateway': 'http://xs.szjietu.com/gateway/mer/order/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(d, key):
    s = 'merNo={}&merSecret={}&amount={}&payType={}'.format(
        d['merNo'], key, d['amount'], d['payType']
    )
    _LOGGER.info("yutoupay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'status={}&payType={}&orderNo={}&orderStatus={}&orderAmount={}&payoverTime={}&merSecret={}'.format(
        d['status'], d['payType'], d['orderNo'], d['orderStatus'], d['orderAmount'], d['payoverTime'], key
    )
    _LOGGER.info("yutoupay generate_notify_sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yutoupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 微信	WEIXIN
# 支付宝	ALIPAY
# 快捷支付	KUAIJIE
# 网银	WY
# 微信H5支付	WXH5
# 支付宝H5支付	ALIH5
# QQH5支付	QQH5
# QQ支付	QQPAY
# 银联扫码	YLSM
# 京东H5	JDH5
# 京东支付	JDPAY
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'WXH5'
    elif service == 'alipay':
        payType = 'ALIH5'
    elif service == 'qq':
        payType = 'QQH5'
    elif service == 'quick':
        payType = 'KUAIJIE'
    else:
        payType = 'JDH5'
    return payType


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merNo', app_id),
        ('orderNo', str(pay.id)),
        ('amount', str(pay_amount)),
        ('returnUrl', '{}/pay/api/{}/yutoupay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyUrl', '{}/pay/api/{}/yutoupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('payType', _get_pay_type(service)),
        ('isDirect', '0'),
        ('bankSegment', ''),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("yutoupay create: %s", parameter_dict)
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("yutoupay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("yutoupay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('yutoupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderStatus'])
    trade_no = ''
    total_fee = float(data['orderAmount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    # SUCCESS成功，FAILED失败，WAITTING_PAYMENT等待支付
    if trade_status == 'SUCCESS':
        _LOGGER.info('yutoupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merKey', app_id),
        ('merSecret', api_key),
        ('orderNo', str(pay_order.id)),
    ))
    _LOGGER.info('yutoupay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('yutoupay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['orderStatus'])
        total_fee = float(data['orderAmount'])
        trade_no = ''

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == 'SUCCESS':
            _LOGGER.info('yutoupay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
